// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  
  // 直接使用openid作为用户标识
  if (!wxContext.OPENID) {
    return {
      success: false,
      message: '用户未登录'
    }
  }
  
  const userOpenid = wxContext.OPENID
  
  try {
    const { status = 'all', limit = 10, skip = 0 } = event
    
    console.log('获取我的活动参数:', { userOpenid, status, limit, skip })

    // 查询用户活动中继表
    const relayResult = await db.collection('user_activity_relay')
      .where({
        userId: userOpenid
      })
      .get()
    
    if (!relayResult.data || relayResult.data.length === 0) {
      return {
        success: true,
        data: [],
        message: '暂无报名活动'
      }
    }
    
    // 获取用户的活动记录
    const userActivityRelay = relayResult.data[0]
    let activityRecords = userActivityRelay.activityRecords || []
    
    if (activityRecords.length === 0) {
      return {
        success: true,
        data: [],
        message: '暂无报名活动'
      }
    }
    
    // 根据状态筛选活动记录
    if (status !== 'all') {
      let filterStatus
      switch (status) {
        case 'registered':
          filterStatus = 'registered'
          break
        case 'ongoing':
          filterStatus = 'attended'
          break
        case 'finished':
          filterStatus = 'attended'
          break
        default:
          filterStatus = null
      }
      
      if (filterStatus) {
        activityRecords = activityRecords.filter(record => record.status === filterStatus)
      }
    }
    
    // 获取活动ID列表
    const activityIds = activityRecords.map(record => record.activityId)
    
    if (activityIds.length === 0) {
      return {
        success: true,
        data: [],
        message: '暂无相关状态的活动'
      }
    }
    
    // 从activities表获取活动详情
    let activityQuery = db.collection('activities')
      .where({
        _id: db.command.in(activityIds)
      })
    
    // 如果需要按活动本身的状态进一步筛选
    if (status !== 'all') {
      let activityStatus
      switch (status) {
        case 'registered':
          activityStatus = '报名中'
          break
        case 'ongoing':
          activityStatus = '进行中'
          break
        case 'finished':
          activityStatus = '已结束'
          break
        default:
          activityStatus = null
      }
      
      if (activityStatus) {
        activityQuery = activityQuery.where({
          status: activityStatus
        })
      }
    }
    
    // 获取活动详情
    const activityResult = await activityQuery.get()
    
    // 合并活动记录信息和活动详情
    const myActivities = activityResult.data.map(activity => {
      const activityRecord = activityRecords.find(record => record.activityId === activity._id)
      return {
        ...activity,
        registrationInfo: activityRecord,
        registrationTime: activityRecord?.registrationTime,
        paymentStatus: activityRecord?.paymentStatus,
        registrationStatus: activityRecord?.status
      }
    })
    
    // 按报名时间排序
    myActivities.sort((a, b) => {
      const timeA = new Date(a.registrationTime || 0)
      const timeB = new Date(b.registrationTime || 0)
      return timeB - timeA
    })
    
    // 分页处理
    const startIndex = skip
    const endIndex = skip + limit
    const paginatedActivities = myActivities.slice(startIndex, endIndex)
    
    console.log('获取到的我的活动数据:', paginatedActivities.length, '条')
    
    return {
      success: true,
      data: paginatedActivities,
      message: '获取成功',
      total: myActivities.length
    }
    
  } catch (error) {
    console.error('获取我的活动失败:', error)
    return {
      success: false,
      data: [],
      message: '获取失败',
      error: error.message
    }
  }
}
